package com.atao.order.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atao.order.Order;
import com.atao.order.properties.OrderProperties;
import com.atao.order.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private OrderProperties orderProperties;

    // 创建订单
    @GetMapping("/create")
    @SentinelResource(value = "create1", blockHandler = "createFallback")
    public Order create(Long userId, Long productId){
        return orderService.create(userId,productId);
    }

    // 获取配置信息
    @GetMapping("/1")
    @SentinelResource(value = "getConfig1", blockHandler = "getConfigFallback")
    public String getConfig(){
        return "timeout:" + orderProperties.getTimeout() +
                " auto-confirm:" + orderProperties.getAutoConfirm()+
                " order.db-url:"+ orderProperties.getDbUrl();
    }

    // 秒杀创建订单
    @SentinelResource(value = "seckill1", blockHandler = "seckillFallback")
    @GetMapping("/seckill")
    public Order seckill(Long userId, Long productId){
        Order order =  orderService.create(userId,productId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    //兜底回调
    //兜底回调
    public Order createFallback(Long userId, Long productId, BlockException e){
        Order order = new Order();
        order.setId(1L);
        order.setUserId(1L);
        order.setNickName("张三");
        order.setAddress("北京");
        order.setProductList(null);
        return order;
    }

    public Order seckillFallback(Long userId, Long productId, BlockException e) {
        Order order = new Order();
        order.setId(Long.MAX_VALUE);
        order.setUserId(userId != null ? userId : 1L);
        order.setNickName("秒杀用户");
        order.setAddress("未知地址");
        order.setProductList(null);
        return order;
    }

    public String getConfigFallback(BlockException e) {
        return "系统繁忙，请稍后再试";
    }


}
